//
//  FileService.m
//  Common
//
//  Created by guoshiqing on 2018/6/1.
//  Copyright © 2018年 www.bitkinetic.com. All rights reserved.
//

#import "FileService.h"
#import "PublicVM.h"
#import "CloudDiskVM.h"

@interface FileService ()
@property (nonatomic, strong) PublicVM *publicVM;
@property (nonatomic, strong) CloudDiskVM *cloudDiskVM;
@property (nonatomic, copy) NSString *domain;
@property (nonatomic, copy) NSURLSessionDownloadTask *downloadTask;
@end

@implementation FileService

#pragma 注册返回
- (void)registerSuccessBlock:(String2Block)successBlock
           WithProgressBlock:(ProgressBlock)progressBlock
            WithFailureBlock:(StringBlock)failureBlock
{
    _successBlock = successBlock;
    _progressBlock = progressBlock;
    _failureBlock = failureBlock;
}

- (void)registerDownLoadSuccessBlock:(DownLoadSuccessBlock)downLoadSuccess
           WithDownLoadProgressBlock:(DownLoadProgressBlock)downLoadProgress
               WithDownLoadFailBlock:(DownLoadFailBlock)downLoadFail
{
    _downLoadSuccess = downLoadSuccess;
    _downLoadProgress = downLoadProgress;
    _downLoadFail = downLoadFail;
}


// 发送文件请求
- (void)send2ServiceWithToken:(NSString *)token andFilePath:(NSString *)url andKey:(NSString *)key
{
    if (nil == token || 0 == token.length) return;
    self.publicVM = [[PublicVM alloc] init];
    
    WEAKSELF
    [self.publicVM sendFileWithToken:token andFilePath:url andKey:key withSuccessBlock:^(NSString *key){
        if (weakSelf.successBlock) {
            weakSelf.successBlock(key, weakSelf.domain);
        }
    } andProgressBlock:^(float progress) {
        if (weakSelf.progressBlock) {
            weakSelf.progressBlock(progress);
        }
    } andFailureBlock:^(NSString *message) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(message);
        }
    }];
}

// 拷贝文件到沙盒，并发送获取token的请求
- (void)sendFileWithImage:(UIImage *)image andImageName:(NSString *)imageName andModuleType:(EPModuleType)type andFileType:(NSString *)fileType
{
    NSString *strUrl = [FileManager saveCacheImage:image fileName:imageName forAppModuleType:type];
    self.publicVM = [[PublicVM alloc] init];
    
    WEAKSELF
    [self.publicVM setBlockWithReturnBlock:^(BaseJSONEntity *returnValue) {
        NSDictionary *dataDic = returnValue.data;
        if ([dataDic isKindOfClass:[NSDictionary class]]) {
            NSString *token = [dataDic objectForKey:@"uploadToken"];
            NSString *key = [dataDic objectForKey:@"key"];
            weakSelf.domain = [dataDic objectForKey:@"domain"];
            [weakSelf send2ServiceWithToken:token andFilePath:strUrl andKey:key];
        }
    } WithErrorBlock:^(BaseJSONEntity *errorValue) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(errorValue.msg);
        }
    } WithFailureBlock:^(BaseJSONEntity *failureValue){
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(failureValue.msg);
        }
    }];
    [self.publicVM getTokenFromServerWithFileType:fileType];
}

/* 上传到云盘 */
// 上传图片到云盘
- (void)sendCloudDiskWithImage:(UIImage *)image andImageName:(NSString *)imageName andTeamId:(NSString *)teamId andFileSize:(NSString *)fileSize
{
    NSString *strUrl = [FileManager saveCacheImageToCloudDisk:image fileName:imageName teamId:teamId];
    self.cloudDiskVM = [[CloudDiskVM alloc] init];
    
    WEAKSELF
    [self.cloudDiskVM setBlockWithReturnBlock:^(BaseJSONEntity *returnValue) {
        NSDictionary *dataDic = returnValue.data;
        if ([dataDic isKindOfClass:[NSDictionary class]]) {
            NSString *token = [dataDic objectForKey:@"uploadToken"];
            NSString *key = [dataDic objectForKey:@"key"];
            weakSelf.domain = [dataDic objectForKey:@"domain"];
            [weakSelf send2ServiceWithToken:token andFilePath:strUrl andKey:key];
        }
    } WithErrorBlock:^(BaseJSONEntity *errorValue) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(errorValue.msg);
        }
    } WithFailureBlock:^(BaseJSONEntity *failureValue){
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(failureValue.msg);
        }
    }];
    [self.cloudDiskVM getCloudStorageTokenWithFileName:imageName andFileSize:fileSize];
}

// 上传视频到云盘
- (void)sendCloudDiskWithVideo:(NSURL *)url andVideoName:(NSString *)videoName andTeamId:(NSString *)teamId andFileSize:(NSString *)fileSize
{
    self.cloudDiskVM = [[CloudDiskVM alloc] init];
    WEAKSELF
    [FM registerSaveSuccessBlock:^(NSString *filePath) {
        [weakSelf upLoadVideoWithVideoPath:filePath];
        [weakSelf.cloudDiskVM getCloudStorageTokenWithFileName:videoName andFileSize:fileSize];
    }];
    
    [FileManager saveCacheVideoToCloudDisk:url fileName:videoName teamId:teamId];
}

- (void)upLoadVideoWithVideoPath:(NSString *)videoPath
{
    self.cloudDiskVM = [[CloudDiskVM alloc] init];
    
    WEAKSELF
    [self.cloudDiskVM setBlockWithReturnBlock:^(BaseJSONEntity *returnValue) {
        NSDictionary *dataDic = returnValue.data;
        if ([dataDic isKindOfClass:[NSDictionary class]]) {
            NSString *token = [dataDic objectForKey:@"uploadToken"];
            NSString *key = [dataDic objectForKey:@"key"];
            weakSelf.domain = [dataDic objectForKey:@"domain"];
            [weakSelf send2ServiceWithToken:token andFilePath:videoPath andKey:key];
        }
    } WithErrorBlock:^(BaseJSONEntity *errorValue) {
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(errorValue.msg);
        }
    } WithFailureBlock:^(BaseJSONEntity *failureValue){
        if (weakSelf.failureBlock) {
            weakSelf.failureBlock(failureValue.msg);
        }
    }];
}

// 下载文件到本地
- (void)downloadCloudDiskInfoWithUrl:(NSString *)url andTeamId:(NSString *)teamId andFileName:(NSString *)fileName
{
    /* 创建网络下载对象 */
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    /* 下载地址 */
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:1 timeoutInterval:10.0f];
    
    /* 下载路径 */
    NSString *path = [FileManager cloudStoragePathAboutDownLoadWithTeamId:teamId];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    
    WEAKSELF
    /* 开始请求下载 */
    _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
//        NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
        NSString *progressStr = [NSString stringWithFormat:@"%.2f", downloadProgress.fractionCompleted];
        if (weakSelf.downLoadProgress) {
            weakSelf.downLoadProgress([progressStr floatValue]);
        };
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
//        NSLog(@"下载完成");
        if (error) {
            if (weakSelf.downLoadFail) {
                weakSelf.downLoadFail(error.domain);
            }
        } else {
            if (weakSelf.downLoadSuccess) {
                weakSelf.downLoadSuccess();
            }
        }
        
    }];
    [_downloadTask resume];
}

// 取消下载文件
- (void)cancelDownloadCloudDiskInfoWithTeamId:(NSString *)teamId andFileName:(NSString *)fileName
{
    [_downloadTask cancel];
    
    // 删除本地文件
    NSString *path = [FileManager cloudStoragePathAboutDownLoadWithTeamId:teamId];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    if ([filemanager fileExistsAtPath:filePath]) {
        [filemanager removeItemAtPath:filePath error:nil];
    }
}

@end
